package com.maben.udp.config;

import com.maben.udp.handler.UdpServerHandler;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioDatagramChannel;
import io.netty.util.concurrent.DefaultThreadFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PreDestroy;

/**
 * UDP服务的配置文件
 */
@Configuration
@Slf4j
public class UdpServerConfig {

    @Value("${udp.port:20101}")
    private int port;

    @Value("${udp.buffer-size:65536}")
    private int bufferSize;

    private EventLoopGroup eventLoopGroup;
    private Channel channel;


    @Bean(destroyMethod = "close")
    public Channel udpChannel(UdpServerHandler handler) throws InterruptedException {
        eventLoopGroup = new NioEventLoopGroup(new DefaultThreadFactory("netty-udp-server"));
        
        Bootstrap bootstrap = new Bootstrap()
                .group(eventLoopGroup)
                .channel(NioDatagramChannel.class)
                .option(ChannelOption.SO_BROADCAST, true) // 支持广播
                .option(ChannelOption.SO_RCVBUF, bufferSize) //Socket Option Receive Buffer（接收缓冲区）: 65536=64KB 接收缓冲区
                .option(ChannelOption.SO_SNDBUF, bufferSize) //Socket Option Send Buffer（发送缓冲区）：65536=64KB 发送缓冲区
                .handler(handler);

        channel = bootstrap.bind(port).sync().channel();
        log.info("====启动udp监听,port:{}",port);
        return channel;
    }

    @PreDestroy
    public void shutdown() {
        if (channel != null) {
            channel.close();
        }
        if (eventLoopGroup != null) {
            eventLoopGroup.shutdownGracefully();
        }
        System.out.println(Thread.currentThread()+",UDP服务器已停止");
    }
}
    